"""
用户相关API路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.database import get_db
from app import models, schemas

router = APIRouter()


@router.post("/users", response_model=schemas.UserResponse)
async def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    """
    创建用户（小程序登录时调用）
    
    - **openid**: 微信openid
    - **nickname**: 用户昵称
    - **avatar**: 用户头像URL
    """
    # 检查用户是否已存在
    existing_user = db.query(models.User).filter(
        models.User.openid == user.openid
    ).first()
    
    if existing_user:
        return existing_user
    
    # 创建新用户
    db_user = models.User(
        openid=user.openid,
        nickname=user.nickname,
        avatar=user.avatar
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


@router.get("/users/{user_id}", response_model=schemas.UserResponse)
async def get_user(user_id: int, db: Session = Depends(get_db)):
    """
    获取用户信息
    
    - **user_id**: 用户ID
    """
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user


@router.get("/users/openid/{openid}", response_model=schemas.UserResponse)
async def get_user_by_openid(openid: str, db: Session = Depends(get_db)):
    """
    通过openid获取用户信息
    
    - **openid**: 微信openid
    """
    user = db.query(models.User).filter(models.User.openid == openid).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user


@router.put("/users/{user_id}", response_model=schemas.UserResponse)
async def update_user(
    user_id: int,
    user_update: schemas.UserBase,
    db: Session = Depends(get_db)
):
    """
    更新用户信息
    
    - **user_id**: 用户ID
    - **nickname**: 用户昵称
    - **avatar**: 用户头像URL
    """
    db_user = db.query(models.User).filter(models.User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    if user_update.nickname:
        db_user.nickname = user_update.nickname
    if user_update.avatar:
        db_user.avatar = user_update.avatar
    
    db.commit()
    db.refresh(db_user)
    return db_user

